package transcation;

import common.MessageConnectionFactory;

import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;
import javax.jms.*;

/**
 * Created with Intel IDEA.
 *
 * @Auther: gjt
 * @Date: 2024/11/16 10:35
 */
public class ExceptionAOP {

    @AroundInvoke
    public Object sendException(InvocationContext ctx) {
        String name = ctx.getClass().getName();

        String op = name + "->" + ctx.getMethod().getName();

        try {
            // 执行方法 (被拦截)
            return ctx.proceed();
        } catch (Exception e) {
            try {
                TopicConnectionFactory instance = MessageConnectionFactory.getInstance();
                TopicConnection topicConnection = instance.createTopicConnection();
                TopicSession topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
                Topic topic = topicSession.createTopic("topic1");
                topicConnection.start();

                TopicPublisher publisher = topicSession.createPublisher(topic);
                TextMessage textMessage = topicSession.createTextMessage(op + ":" + e);
                publisher.publish(textMessage);

                topicSession.close();
                topicConnection.close();
            } catch (JMSException ex) {
                throw new RuntimeException(ex);
            }
        }
        return null;
    }
}
